<template>
  <base-modal
    :show.sync="visible"
    :title="title"
    width="600px"
  > 
    <div class="material-reconfirm-container">

      <!-- 选择禁用的产品 -->
      <template v-if="forbiddenProductData.length">
        <div class="title">{{$t('task.detail.components.disableProduct')}}</div>
        <div class="table-content">
          <el-table
            v-table-style
            stripe
            border
            :data="forbiddenProductData"
            ref="disableTable"
            header-row-class-name="base-table-header-v3"
            class="bbx-normal-list-box"
            @selection-change="handleSelectionChange"
          >
            <template slot="empty">
              <BaseListForNoData :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
            </template>

            <el-table-column type="selection" fixed align='center' width="44"></el-table-column>
            <el-table-column
              v-for="column in returnColumns"
              :key="column.field"
              :prop="column.field"
              :label="column.label"
              :fixed="column.fixed"
              :min-width="column.width"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <template >{{scope.row[column.field]}}</template>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>

      <template v-if="createProductData.length">
        <!-- 新建产品 -->
        <div class="title">{{$t('task.detail.components.createProduct')}}<span v-if="productSnUnique">{{$t('task.detail.components.createProductTip')}}</span></div>
        <div class="table-content">
          <el-table
            stripe
            border
            :data="createProducts"
            ref="table"
            header-row-class-name="base-table-header-v3"
            class="bbx-normal-list-box"
          >
            <template slot="empty">
              <BaseListForNoData :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
            </template>

            <el-table-column
              v-for="column in eliminateColumnsData"
              :key="column.field"
              :prop="column.field"
              :label="column.label"
              :fixed="column.fixed"
              :min-width="column.width"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <template v-if="column.field === 'action'">
                  <el-button type="text" @click="deleteProduct(scope.row, scope.$index)">{{$t('common.base.delete')}}</el-button>
                </template>

                <template v-else-if="column.field === 'name'">
                  <el-input
                    v-model="scope.row.name"
                    :placeholder="$t('common.placeholder.input')"
                  ></el-input>
                </template>

                <template v-else-if="column.field === 'serialNumber'">
                  <el-input
                    v-model="scope.row.serialNumber"
                    :placeholder="$t('common.placeholder.input')"
                  ></el-input>
                </template>


                <template v-else-if="column.field === 'catalogId'">
                  <el-select
                    class="form-material-verify-select"
                    v-model="scope.row.catalogId"
                    @change="selectCatalogId(scope.row)"
                  >
                    <el-option
                      v-for="item in scope.row.catalogs"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </template>
                <template v-else-if="column.field === 'qualityStartTime'">
                  <el-date-picker
                    v-model="scope.row.qualityStartTime"
                    :picker-options="datePickerStartOption(scope.row.qualityEndTime)"
                    type="date"
                    prefix-icon="iconfont icon-fd-date"
                    clearable
                    :placeholder="$t('task.tip.planTaskTip6')"
                    value-format="timestamp"
                  >
                  </el-date-picker>
                </template>
                <template v-else-if="column.field === 'qualityEndTime'">
                  <el-date-picker
                    v-model="scope.row.qualityEndTime"
                    :picker-options="datePickerEndOption(scope.row.qualityStartTime)"
                    type="date"
                    prefix-icon="iconfont icon-fd-date"
                    clearable
                    :placeholder="$t('task.tip.planTaskTip6')"
                    value-format="timestamp"
                  >
                  </el-date-picker>
                </template>
                <template v-else>{{scope.row[column.field]}}</template>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>

    </div>
    
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="pending" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" :disabled="pending" @click="submit">{{$t('common.base.submit')}}</el-button>
    </div>
  </base-modal>
</template>
<script>
import i18n from '@src/locales'
import { cloneDeep } from 'lodash';
import { useDatePicker } from 'pub-bbx-utils'

const { getDisabledDateForPicker } = useDatePicker()

export default {
  name: 'material-reconfirm-dialog',
  props: {
    initData: {
      type: Object,
      default: () => ({})
    },
    returnColumns: {
      type: Array,
      default: () => ([])
    },
    eliminateColumns: {
      type: Array,
      default: () => ([])
    },
  },
  data() {
    return {
      pending: false,
      visible: false,
      columns: [],
      // 禁用产品数据
      forbiddenProductData: [],
      // 新建产品数据
      createProductData: [],
      multipleSelection: [],
    }
  },
  computed: {
    title() {
      if(this.forbiddenProductData?.length > 0 && this.createProductData?.length > 0) {
        return i18n.t('task.detail.components.reconfirmDialogTitle')
      } else if(this.forbiddenProductData?.length > 0) {
        return i18n.t('task.detail.components.reconfirmDialogTitle1')
      } else if(this.createProductData?.length > 0) {
        return i18n.t('task.detail.components.reconfirmDialogTitle2')
      }
      return ''
    },
    customer() {
      return this.initData?.task?.customer || {}
    },
    createProducts() {
      return this.createProductData.map(item => {
        return {
          ...item,
          type: item.catalogs,
          customer: this.customer.name,
          qualityStartTime: '',
          qualityEndTime: '',
          catalogId: item.catalogs?.length ? item.catalogs[0].id : '',
        }
      })
    },
    eliminateColumnsData() {
      return [...this.eliminateColumns, {
        label: i18n.t('common.base.operation'),
        field: 'action',
        fixed: 'right',
        width: 80,
        render: (h, params) => {
          return h('div', [
            h('el-button', {
              props: {
                type: 'text',
                size: 'small'
              },
              on: {
                click: () => {
                  this.$emit('delete', params.row)
                }
              }
            }, i18n.t('base.delete'))
          ])
        }
      }]
    },
    // 产品编号唯一校验
    productSnUnique() {
      return this.initData.productSnUnique || false
    },
  },
  methods: {
    datePickerStartOption(qualityEndTime) {
      return {
        disabledDate(date) {
          return getDisabledDateForPicker(date, qualityEndTime)
        }
      }
    },
    datePickerEndOption(qualityStartTime) {
      return {
        disabledDate(date) {
          return getDisabledDateForPicker(qualityStartTime, date)
        }
      }
    },
    open(forbiddenProductData, productsData) {
      this.forbiddenProductData = forbiddenProductData.map(item => {
        if(item.qualityStatus) {
          item.qualityStatus = item.qualityStatus === 'IN' ? i18n.t('common.base.warranty') : i18n.t('common.base.surrender')
        }
        return {
          ...item,
          catalogId: item.type,
          customer: this.customer.name,
        }
      })

      try {
        const itemData = []
        productsData.forEach((item, index) => {
          item.catalogId = item.catalogs?.length ? item.catalogs[0].id : '',
          item.catalogName = item.catalogs?.length ? item.catalogs[0].name : ''
          item.number = Number(item.number)
          if(item.number > 1 && !item.isSnManage) {
            const arr = new Array(item.number)
            for (let i = 0; i < arr.length; i++) {
              arr[i] = cloneDeep(item)
            }
            itemData.push(...arr)
          } else {
            itemData.push(item)
          }
        })
        this.createProductData = itemData
      } catch(error) {
        console.log(error)
      }
      
      this.visible = true

      this.$nextTick(() => {
        this.forbiddenProductData.forEach(item => {
          this.$refs.disableTable?.toggleRowSelection(item, true)
        })
      })
    },
    toggleSelection(rows, check) {
      this.$refs.disableTable.toggleRowSelection(rows)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    selectCatalogId(row) {
      console.log(row, 'selectCatalogId')
    },
    deleteProduct(row, index) {
      this.createProducts.splice(index, 1)
    },
    submit() {
      const banProductIds = this.multipleSelection.map(item => item.id)
      const createProByMat = this.createProducts.map(item => {
        return {
          name: item.name,
          customerId: this.customer.id,
          serialNumber: item.serialNumber,
          catalogId: item.catalogId,
          type: item.catalogName,
          qualityStartTime: item.qualityStartTime,
          qualityEndTime: item.qualityEndTime,
        }
      })
      this.visible = false
      this.$emit('submit', { banProductIds, createProByMat } )
    }
  },
  mounted() {
     
  }
}
</script>
<style lang="scss" scope>
.material-reconfirm-container {
  padding: 10px 20px;
  .title {
    font-size: 14px;
    font-weight: bold;
    color: #262626;
    padding: 10px 0;
    span {
      font-size: 12px;
      color: #595959;
      font-weight: 500;
      margin-left: 10px;
    }
  }
  .table-content {
    margin-bottom: 10px;
  }
}
</style>